package top.maochang.hou.dao.impl;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import top.maochang.hou.dao.SecurityDao;
import top.maochang.hou.dao.UserDao;
import top.maochang.hou.entity.SysUser;
import top.maochang.hou.utils.DigestsUtil;
import top.maochang.hou.utils.EncodesUtil;
import top.maochang.hou.utils.JDBCUtlis;
import top.maochang.hou.vo.PageVo;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;


public class UserDaoImpl implements UserDao {

    @Override
    public boolean login(UsernamePasswordToken token) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        }catch (Exception ex){
            ex.printStackTrace();
            return false;
        }
        return subject.isAuthenticated();
    }

    @Override
    public void logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

    @Override
    public List<SysUser> getUsers(SysUser user, PageVo pageVo) throws SQLException {
        String sql = "select " +
                "id           id," +
                "username     userName," +
                "password     passWord," +
                "name         name," +
                "phone        phone," +
                "head_url     headUrl," +
                "dept_id      deptId," +
                "post_id      postId," +
                "description  description," +
                "status       status," +
                "create_time  createTime," +
                "update_time  updateTime," +
                "is_deleted   isDeleted," +
                "salt         salt," +
                "sex          sex" +
                " from `sys_user` where 1=1";
        if(user.getUserName()!=null&&user.getUserName()!=""){
            sql+=" and  userName='"+user.getUserName()+"'";
        }
        if(user.getName()!=null&&user.getName()!=""){
            sql+=" and  name='"+user.getName()+"'";
        }
        if(user.getSex()!=null&&user.getSex()!=""){
            sql+=" and  sex='"+user.getSex()+"'";
        }
        sql+=" limit "+pageVo.getOffset()+","+pageVo.getLimit()+" ";
        List<SysUser> sysUser = JDBCUtlis.queryForList(SysUser.class, sql);
        return sysUser;
    }

    @Override
    public Long getUsersCount(){
        String sql ="select count(id) from  sys_user";
        System.out.println(sql);
        Long i = (Long) JDBCUtlis.queryForSingleValue(sql);
        return i;
    }

    @Override
    public boolean delUser(String id) throws SQLException {
        String sql="delete from sys_user where id=?";
        int update = JDBCUtlis.update(sql, id);
        return update>0;
    }

    @Override
    public boolean updateStatus(String id,String state) throws SQLException {
        String sql="update  sys_user  set `status`=?  where id=?";
        int update = JDBCUtlis.update(sql,state,id);
        return update>0;
    }

    @Override
    public boolean addUser(SysUser sysUser) throws SQLException {
        sysUser.setSalt(DigestsUtil.generateSalt());//盐值
        sysUser.setPassWord(DigestsUtil.sha1(sysUser.getPassWord(), sysUser.getSalt())); //密码
        //============================
        sysUser.setStatus(1); //状态
        sysUser.setDeptId(1); //部门id
        sysUser.setPostId(2); //岗位id
        sysUser.setDescription("超级好员工");//描述信息
        sysUser.setHeadUrl("https://avatars.githubusercontent.com/u/499550?v=4");
        sysUser.setIsDeleted(0);//逻辑删除标识
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        //============================
        String sql = "insert into sys_user values (null,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        int count = JDBCUtlis.update(sql
                , sysUser.getUserName()
                , sysUser.getPassWord()
                , sysUser.getName()
                , sysUser.getPhone()
                , sysUser.getHeadUrl()
                , sysUser.getDeptId()
                , sysUser.getPostId()
                , sysUser.getDescription()
                , sysUser.getStatus()
                , sysUser.getCreateTime()
                , sysUser.getUpdateTime()
                , sysUser.getIsDeleted()
                , sysUser.getSalt()
                , sysUser.getSex());
        System.out.println(count);
        return count>0;
    }


    @Override
    public boolean addUserRole(String [] ids,String userId) throws SQLException {
            int count=0;
            for (String id : ids) {
                String sql = "insert into  sys_user_role values(null,?,?,?,?,?)";
                count+= JDBCUtlis.update(sql,id,userId,new Date(),new Date(),0);
                System.out.println(count);
            }
            if(count==ids.length){
                return true;
            }else {
                return false;
            }
    }

    @Override
    public boolean delUserRole(String roleId, String userId) throws SQLException {
        String sql = "delete from sys_user_role where role_id=? and user_id=?";
        int update = JDBCUtlis.update(sql, roleId, userId);
        System.out.println(update);
        return update>0;
    }

    @Override
    public Long addUserMaxId() {
        String sql="select MAX(id) from sys_user";
        Long zhi= (Long) JDBCUtlis.queryForSingleValue(sql);
        return zhi;
    }

    @Override
    public boolean updateUser(SysUser sysUser,String ids[]) throws SQLException {
        //0.先根据用户名查id
        SecurityServiceImpl securityService=new SecurityServiceImpl();
        SysUser passwordByLoginName = securityService.findPasswordByLoginName(sysUser.getUserName());
        //1.先删除用户角色关联信息表 del-user_role,关于此用户的所有角色
        String delSql="delete from sys_user_role where  user_id=?";
        int update1 = JDBCUtlis.update(delSql, passwordByLoginName.getId());
        //2.修改用户表用户信息 sys_user
        String updateSql="update sys_user  set name=?,sex=?,phone=? where id=?";
        int update2 = JDBCUtlis.update(updateSql, sysUser.getName(),sysUser.getSex(),sysUser.getPhone(),passwordByLoginName.getId());
        //3.添加用户角色关联表信息表 update-user_role,
        boolean update3 = this.addUserRole(ids, passwordByLoginName.getId().toString());
        if(update1>0&&update2>0&&update3==true){
            return  true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateUserPassword(String UserId) throws SQLException {
        String updateSql="update  sys_user  set `password`=?,salt=?  where id=?";
        String salt=DigestsUtil.generateSalt();
        String password= DigestsUtil.sha1("root", salt);
        int update = JDBCUtlis.update(updateSql, password, salt);
        return update>0;
    }


}
